// Copyright 2000-2020 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.intellij.sdk.toolWindow;

import com.intellij.icons.AllIcons;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.intellij.sdk.NotifyGroupConstants;
import org.intellij.sdk.listener.DateRefreshMessagePublisher;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.atomic.AtomicBoolean;

public class MyToolWindowFactory implements ToolWindowFactory {
    AtomicBoolean icon = new AtomicBoolean(true);

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        MyToolWindow myToolWindow = new MyToolWindow(toolWindow, project);
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        Content content = contentFactory.createContent(myToolWindow.getContent(), "", false);
        toolWindow.getContentManager().addContent(content);

        project.getMessageBus().connect().subscribe(DateRefreshMessagePublisher.TOPIC, (date, fireProject) -> {
            if (icon.get()) {
                toolWindow.setIcon(AllIcons.Actions.Cancel);
                icon.set(false);
            } else {
                toolWindow.setIcon(AllIcons.Actions.Refresh);
                icon.set(true);
            }

            Notification notify = NotifyGroupConstants.NOTIFICATION_GROUP
                    .createNotification("修改toolWindow图标的同时,给" + fireProject.getName() + "发通知" + date, NotificationType.INFORMATION);
            notify.notify(fireProject);
        });
    }

}
